package com.magi.factory;

import com.magi.core.TableMetaData;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class MysqlTableMetaFactory implements ITableMetaDateFactory {

    private final DatabaseMetaData metaData;

    private final String databaseName;

    public MysqlTableMetaFactory(String databaseName, DatabaseMetaData metaData) {
        if (databaseName == null || databaseName.isEmpty()) { throw new RuntimeException("databaseName could not be null or empty"); }
        this.databaseName = databaseName;
        this.metaData = metaData;
    }

    @Override
    public TableMetaData getMateDate(String tableName) throws SQLException {
        ResultSet resultSet = metaData.getColumns(databaseName, null, tableName, null);
        List<TableMetaData.Column> columnList = new ArrayList<>();
        while(resultSet.next()) {
            columnList.add(new TableMetaData.Column(
                    resultSet.getString("TYPE_NAME"),
                    resultSet.getString("COLUMN_NAME")
            ));
        }
        if (columnList.size() > 0) {
            return new TableMetaData(tableName, columnList);
        }
        return null;
    }

    @Override
    public List<TableMetaData> getAllMateDate() throws SQLException {
        ResultSet resultSet = metaData.getTables(databaseName, null, null, null);
        List<TableMetaData> ret = new ArrayList<>();
        while(resultSet.next()) {
            ret.add(this.getMateDate(resultSet.getString("TABLE_NAME")));
        }
        return ret;
    }
}
